﻿#define _CRT_SECURE_NO_WARNINGS 1
// CMainDlg.cpp: 实现文件
//

#include "CMainDlg.h"
#include "afxdialogex.h"
#include "resource.h"
#include "CApp.h"


// CMainDlg 对话框

IMPLEMENT_DYNAMIC(CMainDlg, CDialogEx)

void CMainDlg::ReadFileText(LPCTSTR path)
{
	FILE* pf = _tfopen(path, L"rb");	// 打开文件
	if (!pf)
	{
		perror("fopen");
		return;
	}

	// 获取文件大小
	size_t n = CApp::GetFileSize(pf);

	if (n > 0)
	{
		// 读取文件
		char* p = new char[n + 2];
		auto nSize = fread(p, 1, n, pf);
		p[nSize] = 0;
		p[nSize + 1] = 0;

		// 设置进文本框
		//SetDlgItemText(hwndDlg, IDC_EDIT1, p);

		// 将文件都转成文本框编码格式(ANSI)
		ParseText(p);

		delete[]p;
	}

	fclose(pf);
}

void CMainDlg::ParseText(LPSTR text)
{
	/*
		ANSI没有文件头
		UTF-16 BE 大端，文件头是0xFFFE
		UTF-16 LE 小端，文件头是0xFEFF
		UTF-8 带有BOM头的，文件头是0xEF BB BF
		UTF-8 没有文件头，需要判断是否满足UTF-8编码格式
	*/
	wchar_t* q = nullptr;
	switch (*(WORD*)text)
	{
	case 0xFFFE:
	{
		// UTF - 16 BE 大端，文件头是0xFFFE
		// 所以这里进行一下转化，转为小端
		CApp::ConvertToSmall(text);
	}
	case 0xFEFF:
	{
		// UTF-16 LE 小端，文件头是0xFEFF
		SetDlgItemText(IDC_TEXT, (LPCTSTR)q + 2);
		delete[]q;
	}
	return;
	case 0xBBEF:
		if (text[2] == (char)0xBF)
		{
			q = CApp::UTF8ToUnicode(text + 3);
			SetDlgItemText(IDC_TEXT, q);
			delete[]q;
		}
		return;
	}

	// 判断是否为不带BOM头的UTF-8
	if (CApp::CheckUTF8(text))
	{
		q = CApp::UTF8ToUnicode(text);
		SetDlgItemText(IDC_TEXT, q);
		delete[]q;
	}
	else
	{
		// 除此之外就是ANSI
		q = CApp::ANSIToUnicode(text);
		SetDlgItemText(IDC_TEXT, q);
		delete[]q;
	}
}

CMainDlg::CMainDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_DIALOG1, pParent)
{

}

CMainDlg::~CMainDlg()
{
}

void CMainDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}


BEGIN_MESSAGE_MAP(CMainDlg, CDialogEx)
	ON_WM_DROPFILES()
END_MESSAGE_MAP()


// CMainDlg 消息处理程序


void CMainDlg::OnDropFiles(HDROP hDrop)
{
	// 读取第一个文件的内容
	TCHAR path[MAX_PATH];
	int nCount = DragQueryFile(hDrop, 0, path, _countof(path));
	ReadFileText(path);
	DragFinish(hDrop);		// fclose(pf);
	CDialogEx::OnDropFiles(hDrop);
}
